package com.ciaojian.timer.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ciaojian.core.enums.business.OrderOrderTypeEnum;
import com.ciaojian.core.model.Store;
import com.ciaojian.core.model.StorePerformance;
import com.ciaojian.core.util.LogUtil;
import com.ciaojian.timer.service.OrderServiceImpl;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 统计各门店每天的业绩
 *
 * @author Atlakyn
 */
@Component
public class CounterStorePerformanceScheduled {
    @Resource
    private OrderServiceImpl orderService;

    @Scheduled(cron = "${scheduled.cron.counterStorePerformanceTask}")
    public void counterStorePerformance() {
        Date curDate = new Date();
        LambdaQueryWrapper<Store> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Store::getBusinessType, 0);
        List<Store> storeList = new Store().selectList(lambdaQueryWrapper);
        storeList.forEach(store -> {
            List<Map<String, Object>> mapList = orderService.getBaseMapper().sumSalesOfStore(store.getId(), curDate, curDate);
            mapList.forEach(m -> {
                Integer orderType = Integer.valueOf(m.get("orderType").toString());
                StorePerformance storePerformance = new StorePerformance();
                storePerformance.setType(OrderOrderTypeEnum.getSexEnumByCode(orderType));
                storePerformance.setStoreId(store.getId());
                storePerformance.setDate(curDate);
                storePerformance.setPerformanceAmount(new BigDecimal(String.valueOf(m.get("payTotal"))));
                try {
                    storePerformance.insert();
                } catch (Exception e) {
                    LogUtil.writeDbErrorLog(e.getMessage());
                }
            });
        });
    }
}
